package com.example.test.chapter8.datepicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

import com.example.test.R;
import com.example.test.chapter8.MainChapter8;

public class MyDatePickerActivity extends Activity {
	private TextView dateDisplay;
	private Button pickDate;
	private int month;
	private int year;
	private int day;
	static final int DATE_DIALOG_ID = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.datepicker);
		dateDisplay = (TextView) findViewById(R.id.dateDisplay);
		pickDate = (Button) findViewById(R.id.pickDate);
		pickDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		Calendar calendar = Calendar.getInstance();
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH);
		day = calendar.get(Calendar.DAY_OF_MONTH);
		updateDisplay();
		Button btn = (Button) findViewById(R.id.backpage);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						MainChapter8.class);
				startActivity(intent);
				finish();
			}
		});
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, dateSetListener, year, month, day);
		}
		return null;
	}

	public void updateDisplay() {
		dateDisplay.setText(new StringBuffer().append(month + 1).append(" - ")
				.append(day).append(" - ").append(year));
	}

	private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int yearm, int monthOfYear,
				int dayOfMonth) {
			year = yearm;
			month = monthOfYear;
			day = dayOfMonth;
			updateDisplay();
		}
	};

}
